package types

import (
	"fmt"

	"gitee.com/thubcc/p2pgit/constant"
)

// Puter write pack interfce
type Puter interface {
	Put([]byte) error
	Open(bool) error
	Close() error
	Split() (SomePuter, error)
}

// SomePuter some puters
type SomePuter []Puter

// Split split ith puter
func (ipps *SomePuter) Split(i int) (ops SomePuter, tobeDel Puter, err error) {
	ips := *ipps
	if i >= len(ips) {
		err = fmt.Errorf("out of total")
		return
	}
	tobeDel = ips[i]
	var s []Puter
	s, err = tobeDel.Split()
	ops = append(ips[:i], ips[i+1:]...)
	ops = append(ops, s...)
	return
}

// Put put raw to some pack file
func (ipps *SomePuter) Put(raw []byte) (err error) {
	ips := *ipps
	for k, v := range ips {
		err = v.Put(raw)
		if err == constant.ErrorNeedSplit {
			*ipps, _, err = ips.Split(k)
		}
		if err != nil {
			return
		}
	}
	return
}
